# coding=utf-8
import requests
import json
from utils.zentao import ZenTaoBusiness


class ZenTaoCase(ZenTaoBusiness):
    """子类-用例导入"""
    
    @classmethod
    def get_zt_modules(cls, r_session, product_id, modules_id):
        """获取产品用例模块的所有模块名-根据modules_id
        :return:
        """
        if modules_id:
            prefix_param = cls._query_params_new('tree', 'browse', cls.t,
                                                 dy_params={'productID': product_id,
                                                            'view': 'case',
                                                            'moduleID': modules_id,
                                                            'branch': 0})
        else:
            prefix_param = cls._query_params_new('tree', 'browse', cls.t,
                                                 dy_params={'productID': product_id,
                                                            'view': 'case'})
        case_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = case_url
        res = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
        if res.status_code == 200:
            data = json.loads(json.loads(res.text).get('data')).get('sons')
            zt_first_modules = {d.get('name'): d.get('id') for d in data}
            return zt_first_modules
    
    # 模块的新增查询
    @classmethod
    def according_name_find_ib(cls, title, r_session):
        """根据名称获取产品id
        :param title:
        :param r_session:
        :return:
        """
        try:
            library = cls.get_product(r_session)
            for l_id in library:
                if library[l_id].find(title) != -1:
                    return l_id
            return None
        except Exception as e:
            print(str(e))
            return None
    
    @classmethod
    def get_product(cls, r_session):
        """获取所有产品id
        :param r_session:
        :return:
        """
        try:
            # 获取用例库接口param-objectID值固定
            prefix_param = cls._query_params_new('testcase', 'browse', cls.t, dy_params={})
            url = requests.get(cls.zt_base_url, prefix_param).url
            headers = cls.zt_headers
            headers['Referer'] = url
            # 请求获取所有产品接口
            s_data = r_session.get(url=cls.zt_base_url, params=prefix_param, headers=headers)
            if s_data.status_code == 200:
                s_data = json.loads(s_data.text)
                all_library = json.loads(s_data.get('data')).get('products')
                return all_library
            return None
        except Exception as e:
            print(str(e))
            return None
    
    @classmethod
    def get_all_module_id(cls, product_id, r_session):
        """获取指定产品下所有模块
        :param product_id: 产品id
        :param r_session:
        :return:
        """
        try:
            prefix_param = cls._query_params_new('tree', 'browse', cls.t,
                                                 dy_params={'productID': product_id,
                                                            'view': 'case'})
            module_url = requests.get(cls.zt_base_url, prefix_param).url
            headers = cls.zt_headers
            headers['Referer'] = module_url
            res_module = r_session.get(url=cls.zt_base_url, headers=headers, params=prefix_param)
            if res_module.status_code == 200:
                s_module = json.loads(res_module.text)
                all_module = json.loads(s_module.get('data')).get('tree')
                all_module = {module.get('id'): module.get('name') for module in all_module}
                return all_module
            return {}
        except Exception as e:
            print(str(e))
            return {}
    
    @classmethod
    def according_module_name_find_id(cls, module_name, all_module, r_session, lib_id):
        """获取指定名字获取模块id
        :param module_name: 模块名称
        :param all_module: 所有模块
        :param lib_id: 所有模块
        :param r_session:
        :return:
        """
        try:
            if all_module is None:
                all_module = cls.get_all_module_id(lib_id, r_session)
            for m_id, m_name in all_module.items():
                if m_name == module_name:
                    return m_id
            return None
        except Exception as e:
            print(str(e))
    
    @classmethod
    def add_lib_modules(cls, r_session, name, product_id, modules_id=None):
        """添加产品模块
        :param r_session:
        :param name: 模块名称
        :param product_id: 用例库id
        :param modules_id: 模块id
        :return:
        """
        if modules_id:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                 dy_params={'root': product_id, 'viewType': 'case',
                                                            'moduleID': modules_id, 'branch': 0})
        else:
            prefix_param = cls._query_params_new('tree', 'manageChild', 'json',
                                                 dy_params={'root': product_id,
                                                            'viewType': 'case'})
        
        add_modules_url = requests.get(cls.zt_base_url, prefix_param).url
        headers = cls.zt_headers
        headers['Referer'] = add_modules_url
        
        add_modules_data = {
            'modules[]': name,
            'shorts[]': '',
            'parentModuleID': modules_id
        }
        res = r_session.post(url=cls.zt_base_url, headers=headers, params=prefix_param,
                             data=add_modules_data)
        if res.status_code == 200:
            return res.text
    
    @classmethod
    def new_zt_case_sync(cls, r_session, data, case_data=None):
        """禅道用例同步
        :param r_session:会话
        :param case_data:前置条件
        :param data:用例数据
        :return:
        """
        prefix_params = cls._query_params_new('testcase', 'create', cls.t,
                                              dy_params={'productID': data.get('product'),
                                                         'branch': 0,
                                                         'moduleID': data.get('module')})
        params_url = requests.get(cls.zt_base_url, prefix_params).url
        headers = cls.zt_headers
        headers['Referer'] = params_url
        res_case = r_session.post(url=cls.zt_base_url, data=data,
                                  params=prefix_params,
                                  headers=headers)
        if res_case.status_code == 200:
            result = json.loads(res_case.text)
            print(result.get('message'))
    
    # @classmethod
    # def excel_zt_case(cls, r_session, case_data):
    #     """批量导入excel用例
    #     :param case_data:
    #     :param r_session:
    #     :return:
    #     """
    #     try:
    #         for index, data in enumerate(case_data, 1):
    #             print('num:{} 用例标题:{}'.format(index, data.get('title')))
    #             cls.new_zt_case_sync(r_session, data)
    #         return 0, ''
    #     except Exception as e:
    #         print(str(e))
    #         return 1, str(e)
    
    @classmethod
    def key_word(cls, case_content):
        """处理关键词
        :param case_content:
        :return:
        """
        # 用例库名称或者用例名称
        case_title = case_content.split('-')[0]
        key_word = story = ''
        for filed in case_content.split('-')[1:]:
            if filed.find('关键词') != -1:
                key_word = cls.handle_colon(filed, '关键词')
            if filed.find('需求') != -1:
                story = cls.handle_colon(filed, '需求')
        return case_title, key_word, story
